import {reqGetCode,reqFinishRegister,reqUserLogin,reqGetUserInfo,reqUserLogout} from '@/api'

const state = {
    code:'',
    // 用户的唯一标识
    token:localStorage.getItem('token'),
    userInfo:{}
}
const mutations = {
   GETCODE(state,code){
      state.code = code
   },
   USERLOGIN(state,token){
       state.token = token
   },
   GETUSERINFO(state,userInfo){
       state.userInfo = userInfo
   },
   LOGOUT(state){
       state.userInfo = {};
       state.token='';
       localStorage.removeItem('token')
       
    }
}

const actions = {
    // 获取验证码
    async getCode({commit},phone){
        let result = await reqGetCode(phone)
        if(result.code == 200){
            commit('GETCODE',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
        
    },
    // 完成注册
    async finishRegister({commit},params){
       let result = await reqFinishRegister(params)
       console.log(result)
       if(result.code == 200){
           return 'ok'
       }else{
           return Promise.reject(new Error('faile'))
       }
    },
    // 用户登录
   async userLogin({commit},data){
       let result = await reqUserLogin(data)
    //    console.log(result)
       if(result.code == 200){
           commit('USERLOGIN',result.data.token)
           return 'ok'
       }else{
           return Promise.reject(new Error('falie'))
       }
       
    },
    // 通过token获取用户信息
   async getUserInfo({commit}){
        let result = await reqGetUserInfo()
        if(result.code ==200){
            commit('GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
   async logout({commit}){
       let result = await reqUserLogout()
       if(result.code == 200){
           commit('LOGOUT')
           return 'ok'
       }else{
           return Promise.reject(new Error('faile'))
       }
    }
}

const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters
}